<template>
  <div class="real-time-curve" :class="{ 'is-abnormal': sensor.cdState === '1' }">
    <b-echart class="charts" :options="options"></b-echart>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import BEchart from '@/components/b-echart/index.vue'
import { getHisGraph, getHistoryRealTimePushCurve } from '@/api/sensor'
import dayjs from 'dayjs'
import * as echarts from 'echarts'

const props = defineProps({
  sensor: {
    type: Object,
    default: () => {}
  }
})

const options = ref({
  tooltip: {
    trigger: 'axis',
    formatter: function (data) {
      let result = ''
      for (let i = 0; i < data.length; i++) {
        let item = data[i]
        if (i === 0) {
          result += item.data.dateMinute + '<br>'
        }

        result += item.marker + item.data.formatter + '<br>'
      }

      return result
    }
  },
  grid: [
    {
      top: '32',
      left: '48',
      right: '24',
      bottom: '24'
    }
  ],
  xAxis: {
    type: 'category',
    data: [],
    axisLine: {
      lineStyle: {
        color: '#ffffff'
      }
    },
    nameTextStyle: {
      color: '#ffffff'
    }
  },
  yAxis: {
    name: '监测值',
    type: 'value',
    max: function (val) {
      return val.max < 1 ? 1 : val.max
    },
    axisLine: {
      lineStyle: {
        color: '#ffffff'
      }
    },
    nameTextStyle: {
      color: '#ffffff'
    }
  },
  series: [
    {
      type: 'line',
      name: props.sensor.areaLocation,
      data: [],
      symbol: 'none',
      itemStyle: {
        color: '#00ffa7'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: 'rgb(0, 255, 167)'
          },
          {
            offset: 1,
            color: 'rgba(0, 255, 167, 0.1)'
          }
        ])
      },
      step: ''
    }
  ]
})

function formatData(data) {
  let str = ''
  if (data.cdCode) {
    str += data.showValue + ' - ' +  data.cdStateName
  }

  return str
}
async function initChart() {
  const { data } = await getHisGraph({
    cdCode: props.sensor.cdCode,
    cdLocation: props.sensor.cdLocation,
    cdCodes: [props.sensor.cdCode],
    startTime: dayjs().subtract(30, 'minute').format('YYYY-MM-DD HH:mm:ss'),
    endTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
  })
  const sensorData = data.data[0].data
  sensorData.forEach((item) => {
    let step = 'end'
    if (props.sensor.sensorType && props.sensor.sensorType.substr(0, 1) !== '0') {
      step = 'start'
    }
    options.value.series[0].data.push({
      value: item.cdValue,
      formatter: formatData(item),
      dateMinute: item.dateMinute
    })
    options.value.xAxis.data.push(item.dateMinute)
  })
}
async function setChartData() {
  const random = parseInt(Math.random() * 100)

  const {data} = await getHistoryRealTimePushCurve({
    cdCode: props.sensor.cdCode,
    cdLocation: props.sensor.cdLocation,
    cdCodes: [props.sensor.cdCode]
  })
  const res = data.data[0]
  options.value.series[0].data.push({
    value: res.cdValue,
    formatter: formatData(res),
    dateMinute: res.dateMinute
  })
  options.value.xAxis.data.push(res.dateMinute)

  if (options.value.xAxis.data.length > 30) {
    options.value.xAxis.data.shift()
    options.value.series[0].data.shift()
  }
}

const interval = ref()
onMounted(async () => {
  await initChart()
  interval.value = setInterval(async () => {
    await setChartData()
  }, 10000)
})

onUnmounted(() => {
  console.log('unmounted')
  clearInterval(interval.value)
})
</script>
<style scoped lang="scss">
.real-time-curve {
  width: 100%;
  height: 100%;
  display: flex;
  &.is-abnormal{
    
  }
  .sensor-list {
    max-width: 350px;
    flex: 1;
    overflow: hidden;
    :deep(.el-checkbox-group) {
      display: flex;
      flex-direction: column;
      gap: calc(8px * var(--scale));
      width: 100%;
      .el-checkbox {
        display: flex;
        width: 100%;
        margin-right: 0;
        background: linear-gradient(180deg, rgba(13, 188, 182, 0.2), rgba(28, 132, 57, 0.2) 100%);
        color: var(--color-white);
        padding: 0 calc(8px * var(--scale));
        .el-checkbox__label {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: space-between;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          .sensor-type {
            background: var(--el-color-primary-dark-2);
            color: var(--color-white);
          }
        }
      }
    }
  }
  .charts {
    flex: 3;
  }
}
</style>
